<template>
  <el-form ref="formRef" :model="formData" label-width="120px">
    <base-layout
      :dialog-close-confirm="false"
      :dialog-title="dialogTitle"
      :dialog-visible="dialogVisible"
      visibleContent2
      @dialog-close="dialogClose">
      <template #searchPanel>
        <el-row>
          <el-col :span="12">出库单基础信息</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="出库编号" prop="outStorageCode">
              <el-input v-model="formData.outStorageCode" disabled  readonly="readonly" placeholder="自动生成"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库门店"  prop="storeId">
              <job-shop v-model="formData.storeId" defaultStoreId  class="w-100"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库仓库" prop="storageId">
              <el-select v-model="formData.storageId" placeholder="请选择" class="w-100" @change="requestStorageSiteList">
                <el-option v-for="item in storageList" :key="item.id" :value="item.id" :label="item.storageName"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="receiptsTime">
              <el-date-picker
                v-model="formData.receiptsTime"
                type="datetime"
                placeholder="请选择"
                disabled
                class="w-100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库类型">
              <el-select
                v-model="formData.outStorageType"
                clearable
                placeholder="请选择"
                class="w-100"
              >
                <el-option
                  v-for="item in dict['精品出库类型']"
                  :key="item.index"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="workOrderCode" v-if="formData.outStorageType != '退货出库'" :label="formData.outStorageType == '销售出库' ? '订单编号' : '调拨单编号'">
              <el-input placeholder="请输入" v-model="formData.workOrderCode" @blur="sourceCodeBlur"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="出库备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark" :rows="6" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel>
        <el-row>
          <el-col :span="12">出库负责人员</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="出库负责人" prop="userName">
              <user-select
                v-model="formData.userName"
                :store-id="formData.storeId"
                @change="userNameHChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="phone">
              <el-input placeholder="请输入" v-model="formData.phone" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel2>
        <el-row type="flex" align="middle">
          <el-col :span="12">出库精品列表</el-col>
          <el-col class="text-right" :span="12">
            <el-button type="primary" icon="el-icon-plus" @click="addProductHandle">添加出库精品</el-button>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <data-table
          has-action
          :is-show-page="false"
          :value="formData.partsList"
          :table-column-attributes="tableColumns"
          :width="160"
        >
          <template #action="{row, $index}">
            <i class="el-icon-delete" title="删除" style="cursor: pointer;"  @click="handleDataDelete(row, $index)"></i>
          </template>
          <div class="total-count" slot="allNum">
            精品总金额:<span class="money-value">￥{{formData.amount}}</span>
            <span class="ml-20">精品总数:</span><span class="count-value">{{formData.partsTotal}}</span>
          </div>
        </data-table>
        <div class="text-right mt-10">
          <span class="total-count">
            出库总金额:<span class="money-value">￥{{formData.amount}}</span>
          </span>
          <el-button v-permission="$route.params.id == 0 ? authConfig.add : authConfig.edit" class="ml-20" type="success" @click="submitHandle">{{$route.params.id == 0 ? '新增' : '更新'}}出库单</el-button>
        </div>
      </template>
      <template #dialog>
        <select-product-form v-if="showProductTable" @select="confirmSelectHandle" :supplier-id="formData.supplierId" />
      </template>
    </base-layout>
  </el-form>
</template>

<script>
import BaseLayout from '@/views/layout/Base'
import DataTable from '@/components/DataTable'
import { JobShop } from '@/components/index'
import SelectProductForm from '@/components/CommonForm/SelectProductForm'
import UserSelect from '@/components/CommonForm/UserSelect'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import { findByStoreIdAndStorageId } from '@/api/after-sale/storehouseManage/positionManage'
import { findByStore } from '@/api/after-sale/storehouseManage/warehouseManage'
import {
  save,
  update,
  editDetailById,
  getStorageCode,
  findSourceCode
} from '@/api/pre-sale/boutiqueStock/putOut'

export default {
  components: { JobShop, BaseLayout, DataTable, SelectProductForm, UserSelect },
  data() {
    this.authConfig = {
      add: 'brandOutStorage:save',
      edit: 'brandOutStorage:update'
    }

    return {
      dialogVisible: false,
      dialogTitle: '精品选择',
      formData: {
        amount: 0,
        outStorageCode: '',
        storeId: '',
        storageId: '',
        supplierId: '',
        receiptsTime: parseTimeToYMDHMS(new Date()),
        outStorageType: '',
        workOrderCode: '',
        remark: '',
        userName: '',
        phone: '',
        partsList: [],
        partsTotal: 0
      },
      tableColumns: [
        { name: '精品编号', value: 'partsCode', type: 'text' },
        { name: '精品名称', value: 'partsName', type: 'text' },
        { name: '一级类别', value: 'partsType', type: 'text' },
        { name: '二级类别', value: 'partsUnit', type: 'text' },
        { name: '仓位', value: 'storageSiteId', type: 'select',
          options: this.storageSiteList,
          action: this.storageSiteChang },
        { name: '仓位编号', value: 'storageSiteCode', type: 'text' },
        { name: '出库数量', value: 'outStorageNum', type: 'inputNumber',
          action: this.calcData },
        { name: '仓位剩余', value: 'alreadyNum', type: 'text' },
        { name: '采购成本', value: 'purchasePrice', type: 'text' },
        {
          name: '销售价',
          value: 'storagePrice',
          type: 'inputNumber',
          action: this.calcData
        },
        { name: '总金额', value: 'amount', type: 'text' }
      ],
      storageList: [], // 仓库
      storageSiteList: [], // 仓位
      showProductTable: false
    }
  },
  computed: {
    tableDataMap() {
      const map = {}
      this.formData.partsList.forEach((item, index) => {
        map[item.partsId] = index
      })
      return map
    },
    storeId() {
      return this.formData.storeId
    }
  },
  watch: {
    storeId() {
      this.requestStorageList()
    }
  },
  methods: {
    sourceCodeBlur() {
      const { outStorageType, workOrderCode } = this.formData
      if (outStorageType && workOrderCode) {
        findSourceCode(outStorageType, workOrderCode).then(res => {
          const data = res.data || []
          if (data.length > 0) {
            const partsList = []

            data.forEach(item => {
              const num = item.returnNum || item.num || item.internalNum || 0
              const price = item.purchasePrice || item.returnPrice || 0

              partsList.push({
                amount: num * price,
                partsCode: item.partsCode,
                partsId: item.partsId,
                partsName: item.partsName,
                partsType: item.partsType,
                partsUnit: item.partsUnit,
                purchasePrice: price,
                internalNum: item.internalNum,
                outStorageNum: num,
                storagePrice: price,
                storageSiteId: '',
                storageSiteCode: '',
                storageSiteName: '',
                alreadyNum: 0 // 已存储数
              })
            })
            this.formData.partsList = partsList
            this.calcCountData()
          }
        })
      }
    },
    addProductHandle() {
      this.showProductTable = true
      this.dialogVisible = true
    },
    handleDataDelete(row, $index) {
      this.formData.partsList.splice($index, 1)
      this.calcCountData()
    },
    submitHandle() {
      const method = this.$route.params.id == 0 ? save : update
      this.$refs.formRef.validate(valid => {
        if (valid) {
          method(this.formData).then(res => {
            const length = this.$store.state.tagsView.visitedViews.length
            this.$store.dispatch('delVisitedViews', this.$route)
            if (length == 2) {
              this.$router.replace({ path: '/' })
            } else {
              this.$router.go(-1)
            }
          })
        }
      })
    },
    confirmSelectHandle(selection) {
      const tableList = []
      selection.forEach(item => {
        if (!this.tableDataMap[item.id]) {
          const price = item.currentPrice || 0
          tableList.push({
            amount: 0,
            partsCode: item.orderNo,
            partsId: item.id,
            partsName: item.name,
            partsType: item.appLargeOne,
            partsUnit: item.appLargeTwo,
            purchasePrice: price,
            internalNum: 0,
            storagePrice: price,
            storageSiteId: '',
            storageSiteCode: '',
            storageSiteName: '',
            alreadyNum: 0,
            outStorageNum: 0
          })
        }
      })
      this.formData.partsList.push(...tableList)
      this.calcCountData()
      this.dialogClose()
    },
    // 仓位改变
    storageSiteChang(row) {
      const { storageSiteId } = row
      const storageSite = this.storageSiteList.find(item => item.id == storageSiteId)
      row.storageSiteCode = storageSite.storageSiteCode
      row.storageSiteName = storageSite.storageSiteName
      row.alreadyNum = storageSite.num
    },
    // 计算当前数据
    calcData(row) {
      const { storagePrice, outStorageNum } = row
      row.amount = outStorageNum * storagePrice
      this.calcCountData()
    },
    // 统计所有数据
    calcCountData() {
      let amount = 0 // 总金额
      let outStorageNum = 0 // 总数量

      this.formData.partsList.forEach(item => {
        amount += item.amount || 0
        outStorageNum += item.outStorageNum || 0
      })
      this.formData.amount = amount
      this.formData.partsTotal = outStorageNum
    },
    // 负责人选择
    userNameHChange(item) {
      this.formData.userName = item.userName
      this.formData.phone = item.phone
    },
    // 请求编辑详情
    requestEditDetail(id) {
      editDetailById(id).then(res => {
        Object.assign(this.formData, res.data)
        const { storeId, storageId } = this.formData
        this.requestStorageSiteList(storeId, storageId)
      })
    },
    // 请求编码
    requestCode() {
      getStorageCode().then(res => {
        this.formData.outStorageCode = res.data
      })
    },
    // 根据门店请求仓库
    requestStorageList() {
      if (!this.formData.storeId) {
        return
      }
      // this.formData.storageId = ''
      findByStore(this.formData.storeId).then(res => {
        this.storageList = res.data

        if (!this.storageList.find(item => item.id == this.formData.storeId)) {
          this.formData.storageId = ''
        }
      })
    },
    // 请求仓位信息
    requestStorageSiteList() {
      const { storeId, storageId } = this.formData
      if (!storeId || !storageId) {
        return
      }
      findByStoreIdAndStorageId(storeId, storageId).then(res => {
        const data = res.data
        data.forEach(item => {
          item.value = item.storageSiteName
        })
        this.tableColumns[4].options = data
        this.storageSiteList = data
      })
    },
    dialogClose() {
      this.showProductTable = false
      this.dialogVisible = false
    }
  },
  created() {
    this.dict = getDict(['精品出库类型'])
  },
  mounted() {
    const { id, outStorageType, sourceCode } = this.$route.params
    this.formData.outStorageType = outStorageType
    this.formData.workOrderCode = sourceCode == 0 ? '' : sourceCode
    if (id != 0) {
      this.requestEditDetail(id)
    } else {
      this.requestCode()
      this.sourceCodeBlur()
    }
  }
}
</script>

<style>

</style>
